# coding:UTF-8
import random
import signal
import sys

import paho.mqtt.client as mqtt
from iniconfig import IniConfig

ini = IniConfig('config.ini')

# 连接信息
client_id = f"py_{random.randint(1000, 9999)}"
host = ini.get('mqtt', 'host')
port = int(ini.get('mqtt', 'port'))
clean_session = bool(ini.get('mqtt', 'clean_session'))
keepalive = int(ini.get('mqtt', 'keepalive'))
username = ini.get('mqtt', 'username')
password = ini.get('mqtt', 'password')


def initMqtt():
    topic_list = [
        (f"athlete-dashboard/sport-athletes-app/device-status/#", 1),
    ]

    def handler(topic: str, payload: bytes):
        print(f"{topic}")

    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print(f"【{host} {port}】mqtt客户端连接成功")
            # 订阅主题
            client.subscribe(topic_list)
        else:
            print(f"【{host} {port}】mqtt客户端连接失败 {rc}")

    def on_message(client, userdata, msg):
        handler(msg.topic, msg.payload)

    def on_subscribe(client, userdata, mid, granted_qos):
        print(f"【{host} {port}】mqtt客户端订阅成功 {mid} {granted_qos}")

    def on_disconnect(client, userdata, rc):
        print(f"【{host} {port}】mqtt客户端断开连接 {rc}")

    mqtt_client = mqtt.Client(client_id=client_id, clean_session=clean_session)
    mqtt_client.username_pw_set(username, password)

    mqtt_client.on_connect = on_connect
    mqtt_client.on_message = on_message
    mqtt_client.on_subscribe = on_subscribe
    mqtt_client.on_disconnect = on_disconnect
    mqtt_client.connect(host, port, keepalive)

    def signal_handler(signum, frame):
        print(f"收到信号 SIGINT={signum}，正在关闭 MQTT 客户端...")
        mqtt_client.loop_stop()
        mqtt_client.disconnect()
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)

    # 保持网络循环，等待消息
    mqtt_client.loop_forever()


if __name__ == "__main__":
    # 初始化MQTT
    initMqtt()
